<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;

class FetchPublicJobData extends Command
{
    protected $signature = 'fetch:public-job-data {year=2025}';
    protected $description = 'Fetch job postings from the API and store them in the database';

    public function handle()
    {
            ini_set('memory_limit', -1);
            set_time_limit(-1);
        $year = $this->argument('year'); // 获取用户自定义的年份
        $client = new Client();
        $page = 1;
        $perPage=500;
        die();
        while (true) {
            try {
                // 发起 GET 请求
                $response = $client->get("https://apis.huatu.com/api/gk/zwb/query", [
                    'query' => [
                        'columns' => '*',
                        'zwk_year' => $year, // 使用用户指定的年份
                        'page' => $page,
                        'per_page'=>$perPage
                    ],
                ]);

                $data = json_decode($response->getBody(), true);
                if ($data['code'] === 200) {
                    // 如果当前页没有数据，则停止循环
                    if (empty($data['data']['data'])) {
                        $this->info('没有更多数据可获取，结束操作。');
                        break;
                    }

                    // 处理数据并存入数据库
                    // foreach ($data['data']['data'] as $item) {
                    //     DB::table('job_postings')->updateOrInsert(
                    //         ['id' => $item['id']], // 查找条件
                    //         $item // 填入数据
                    //     );
                    // }
                    $insertData=$data['data']['data']??[];
                    if(!$insertData){
                        continue;
                    }
                    DB::table('job_postings')->insert(
                        $insertData
                    );

                    $page++;
                } else {
                    $this->error('API 请求失败: ' . $data['msg']);
                    return;
                }
            } catch (\Exception $e) {
                $this->error('请求异常: ' . $e->getMessage());
                return;
            }
        }

        $this->info('数据成功获取并存储到数据库中。');
    }
}